#import <appkit/Application.h>
#import <appkit/Button.h>
#import "ImageView.h"
#import <appkit/NXImage.h>
#import <appkit/Control.h>
#import <sys/param.h>
#import <libc.h>
#import <dpsclient/dpsclient.h>
#import <dpsclient/wraps.h>

void nextImageHandler(DPSTimedEntry teNumber, double now, char *userData)
{
	[(id)userData next:nil];
}
 
@implementation ImageView:View

/* INIT/FREE METHODS */

- initFrame:(NXRect *)frameRect;
/* Init method for newly created image view. It initializes the scaling
 * factors to normal. 
 */
{
    [super initFrame:frameRect];
	//[self setBackgroundGray:NX_LTGRAY];
    scaleFactor.x = scaleFactor.y = 1.0;
	imageList = [[List alloc] init];
	period = 1;
	// [[periodText setDoubleValue:1.0L] display];
	// [slider takeDoubleValueFrom:periodText];
	te = (DPSTimedEntry) NULL;
    return self;
}

   
- free;
/* Free the images on our way out.
 */
{
    [imageList free];
    return [super free];
}



/* PRIVATE METHODS */


- setListToFiles:(const char *const *) filenames
{
	if ([imageList count] > 0) [imageList freeObjects];
    [self setDrawRotation:0.0];
    scaleFactor.x = scaleFactor.y = 1.0;
    [self scale:scaleFactor.x :scaleFactor.y];
	while (filenames[0]) {
		[self setImageToFile:filenames[0]];
		[imageList addObject:image];
		++filenames;
	}
	image = [imageList objectAt:0];
	[self display];
	return self;	
}

- setImageToFile:(const char *)filename;
/* Find the bitmap image rep for the specified name, sets the scaling
 * and rotation back to "normal" and displays new image.
 */
{   
	NXRect extent;
	
    image = [[NXImage alloc] initFromFile:filename];
    [image setScalable:YES];
	[self getBounds:&extent];
	[image setSize:&(extent.size)];
	return self;
}

- drawSelf:(NXRect *)rects :(int)rectCount;
/* Clears the background and has the image draw itself 
 */
{
   NXPoint  ll = {0.0,0.0};
	
   PSsetgray(NX_LTGRAY);
   NXRectFill(&bounds);  /* to be sure to clear background */
   [image composite:NX_COPY toPoint:&ll];
   return self;
}

- next:sender
{
	if ([imageList count]) {
		if ([[imageList lastObject] isEqual:image])
			image = [imageList objectAt:0];
		else
			image = [imageList objectAt:[imageList indexOf:image]+1];
		[self display];
	}
	return self;
}

- startTimer
{
	[periodText setDoubleValue:(1.0/period)];
	te = DPSAddTimedEntry(period, 
			(DPSTimedEntryProc)nextImageHandler, 
			(void *)self, NX_MODALRESPTHRESHOLD);
	return self;
}

- stopTimer
{
	 if ( te ) DPSRemoveTimedEntry(te);
	 return self;
}


- animate:sender
{

	switch([[sender selectedCell] state]) {
		case 0: /* Shut down animation */
				animating = NO;
				[self stopTimer];
				break;
				
		case 1: /* Set up animation */
				animating = YES;
				[self startTimer];
				break;
	}
	return self;
	
}

- setSpeed:sender
{
	period = 1.0/[sender doubleValue];
	[periodText takeDoubleValueFrom:sender];
	if (animating) [[self stopTimer] startTimer];
	return self;
}

@end